package com.ouc.controller;

import com.ouc.common.Result;
import com.ouc.entity.CartItem;
import com.ouc.entity.Order;
import com.ouc.entity.OrderItem;
import com.ouc.service.OrderItemService;
import com.ouc.service.OrderService;
import com.ouc.util.UUIDGenerator;
import com.ouc.vo.OutCartItem;
import com.ouc.vo.OutOrder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * @Name: OrderController
 * @Description:
 * @Author: Mr.Tong
 */
@RestController
@RequestMapping("/order")
@CrossOrigin
@Api(tags = "订单接口", description = "提供订单相关的接口信息")
public class OrderController {

    @Autowired
    private UUIDGenerator uuidGenerator;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    //1、存储用户的订单
    @ApiOperation("提交用户订单")
    @PostMapping("/submit")
    public Result store(@RequestBody Order order) {
        //因为orderNum是自动生成的，所以在插入order和orderitem的时候不需要考虑先后顺序
        String orderNum = uuidGenerator.get16UUID();//生成订单号
        order.setOrderNum(orderNum);//设置订单号
        order.setStartTime(new Timestamp(new Date().getTime()));//设置订单创建时间
        //完成订单的设置
        //得到所有的订单条目
        List<OrderItem> orderItems = order.getOrderItems();
        for (int i = 0; i < orderItems.size(); i++) {
            orderItems.get(i).setOrderNum(orderNum);
        }
        //如果order和orderitem都插入成功
        return (orderService.insert(order)) ?
                Result.ok().data("msg", "插入成功") :
                Result.error().data("warn", "插入失败");
    }


    @ApiOperation("根据用户id获取所有订单")
    @GetMapping("/getorders")
    public Result getOrderItemByUserIdAndPaging(Integer userId) {
        List<OutOrder> allOrdersByPaging = orderService.getAllOrdersByPaging(userId);
        return Result.ok().data("orders", allOrdersByPaging);
    }


}
